<template>
    <div class="app-contenter">
        <el-card>
           <div class="flex-header">
                <el-date-picker v-model="searchForm.time" type="daterange" align="right" unlink-panels clearable
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" class="header-date-picker header-input-mini">
                </el-date-picker>
                <el-input v-model="searchForm.name" placeholder="项目名称" clearable class="header-input-mini"></el-input>
                <el-select v-model="searchForm.tagState" placeholder="标签状态" clearable class="header-input-mini" >
                    <el-option  :label="item.text" v-for="(item, index) in projectStatus" :key="index" :value="item.value"></el-option>
                </el-select>
                 <el-select v-model="searchForm.aiState" placeholder="AI处理状态" clearable class="header-input-mini" >
                    <el-option  :label="item.text" v-for="(item, index) in projectAIStatus" :key="index" :value="item.value"></el-option>
                </el-select>
                <el-select v-model="searchForm.cabinetId" placeholder="存储位置" clearable class="header-input-mini" >
                    <el-option v-for="(item, index) in cabinetList" :key="index" :label="item.name+'号柜'" :value="item.id"></el-option>
                </el-select>
                <el-button class="header-search" type="primary" :icon="Search" @click="SearchFun">搜索</el-button>
                <el-button class="header-search" :icon="Plus" @click="handleAddProject" type="primary" plain>新建项目</el-button>
                <el-button class="header-search" @click="handleAI"  plain type="primary">
                    <template #icon >
                        <el-icon>
                            <svg-icon name="ai" /> 
                        </el-icon>
                    </template>
                    AI处理
                </el-button>
           </div>
        </el-card>
        
        <el-card>
            <el-table :data="tableData" v-loading="loading" stripe style="width: 100%"
                :header-cell-style="headerStyle"
                :cell-style="cellStyle"
                @selection-change="handleSelectionChange"
                @cell-click="handleRowClick"
            >
                <el-table-column type="selection" width="55" fixed="left" @click.stop />
                <el-table-column prop="ct" label="创建时间" min-width="200">
                    <template #default="scope">
                        <span>{{moment(scope.row.ct).format('YYYY-MM-DD HH:mm:ss')}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="项目名称" min-width="300" show-overflow-tooltip/>
                <el-table-column prop="cabinetBoxNames" label="存储位置" min-width="160" show-overflow-tooltip >
                    <template #default="scope">
                        <el-tooltip :content="scope.row.cabinetRemark" :disabled="!scope.row.cabinetRemark" >
                            {{scope.row.cabinetBoxNames}}
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="tagState" label="标签状态" min-width="120">
                    <template #default="scope">
                        <div v-if="projectStatus[scope.row.tagState]">
                            <el-tag :type="projectStatus[scope.row.tagState]?.type">{{projectStatus[scope.row.tagState]?.text }}</el-tag>
                        </div>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column prop="aiState" label="AI处理状态" min-width="140">
                    <template #default="scope">
                        <div v-if="projectAIStatus[scope.row.aiState]">
                            <el-tooltip :content="scope.row.failMsg" :disabled="!scope.row.failMsg" >
                                <el-tag :type="projectAIStatus[scope.row.aiState]?.type">{{projectAIStatus[scope.row.aiState]?.text}}</el-tag>
                            </el-tooltip>
                        </div>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column prop="pageCount" label="文件页数" min-width="120"/>
                <el-table-column prop="documentCount" label="文件数" min-width="120"/>
                <el-table-column prop="finishTime" label="完成时间" min-width="200">
                    <template #default="scope">
                        {{scope.row.finishTime ? moment(scope.row.finishTime).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right" >
                    <template #default="scope">
                        <el-button size="small" type="primary" @click.stop="handleDetail(scope.row)" link>详情</el-button>
                    </template>
                </el-table-column>
           </el-table>
           <Pagination :options="paginationOptions"></Pagination>
        </el-card>
        <!-- 组件式：直接使用 <el-loading> 标签 -->
        <div v-if="AILoading" class="loading-container flexCC el-loading-mask is-fullscreen">
            <div class="container">
                <div class="loading-icon" >
                    <img src="@/assets/images/AIload.gif" alt="">
                </div>
                <p class="text">{{ AILoadingMsg }}</p>
                <!--  -->
                <el-progress :percentage="ProgressNum" :stroke-width="10"  striped striped-flow v-if="AILoading" >
                    <div class="txt">
                        {{(ProgressObj?.progress || 0) +'/' + (ProgressObj.all || 0)}}
                    </div>
                </el-progress>
            </div>
        </div>
    </div>
</template>

<script setup>
import { Plus, Search } from '@element-plus/icons-vue';

import { onMounted, ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import moment  from 'moment';
import { ElLoading, ElMessage } from 'element-plus'
import { projectStatus, projectAIStatus } from '@/utils/static'
import { projectQuery, CabinetQuery, taskProjectAI, taskProgress } from "@/api/project"
import AIsvg from '@/assets/svg/ai.svg'
const router = useRouter();
const ProgressObj = ref({});
const ProgressNum = computed(() => {
    return ((ProgressObj.value.progress || 0) / ProgressObj.value.all) * 100 || 0;
});
const loading = ref(false);
const AILoading = ref(false);
const AILoadingMsg = ref("");
const ProjectIds = ref([]);
const tableData = ref([]);
const cabinetList = ref([]);
const searchForm = ref({
    pageNum:1,
    pageSize:10,
    total:0
})
const getCabinetData = async () => {
    const result = await CabinetQuery();
    if(result.errorCode == 0){
        cabinetList.value = result.data;
    }else{
        cabinetList.value = []
    }
}
onMounted(() => {
    if(!!localStorage.getItem('projectQueryParam')){
        searchForm.value = JSON.parse(localStorage.getItem('projectQueryParam'));
    }
    getProjectData();
    getCabinetData();
})
const getProjectData = async () => {
    loading.value = true;
    const result = await projectQuery(searchForm.value);
    loading.value = false;
    if(result.errorCode == 0){
        tableData.value = result.data;
        // searchForm.value.total = 
    }else{
        tableData.value = []
    }
} 
const SearchFun = ()=>{
    searchForm.value.pageNum = 1;
    localStorage.setItem('projectQueryParam', JSON.stringify(searchForm.value));
    getProjectData();
}
const handleAI = async ()=>{
    if(ProjectIds.value.length == 0){
        return ElMessage.warning('请先选择项目');
    }
    const loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)',
    });
    let  result = await taskProjectAI({
        projectIds:ProjectIds.value
    });
    loading.close();
    if(result.errorCode == 0){
        AILoading.value = true;
        AILoadingMsg.value = result.data.toast;
        processAI(result.data.id);
    }
}
const processAI = async (taskId)=>{
    let  result = await taskProgress({
        taskId:taskId
    });
    if(result.errorCode == 0){
        ProgressObj.value.all = result.data.all;
        ProgressObj.value.progress = result.data.progress;
        if(result.data.all != result.data.progress){
            setTimeout(() => {
                processAI(taskId);
            }, 1000);
        }else{
            ElMessage.success('处理完成');
            getProjectData();
            setTimeout(() => {
                AILoading.value = false;
                ProgressNum.value = 0;
            }, 1500);
        }
    }
}
const handleDetail = (row)=>{
    router.push({ path: '/projectDigital/details', query: { id: row.id } });
    localStorage.setItem('projectQueryParam', JSON.stringify(searchForm.value));
}
const handleRowClick = (row, column, event)=>{
    handleDetail(row);
}

const handleAddProject = ()=>{
    router.push('/projectDigital/addProject');
}
const handleSelectionChange = (val) => {
    ProjectIds.value = val.map(item => item.id); 
}
// 分页配置
const paginationOptions = reactive({
    currentPage: computed(() => searchForm.value.pageNum),
    pageSize: computed(() => searchForm.value.pageSize),
    total: computed(() => searchForm.value.total ?? 0),
    change: getProjectData,
});
// 用 defineOptions 定义组件选项（模拟选项式 API 的路由守卫）
defineOptions({
  // 组件内路由守卫：进入前
  beforeRouteEnter(to, from, next) {
    // console.log('beforeRouteEnter 执行');
    // 通过 next(vm => {}) 访问组件实例
    next();
  },
  // 组件内路由守卫：参数更新
  beforeRouteUpdate(to, from, next) {
    // console.log('beforeRouteUpdate 执行');
    next();
  },
  // 组件内路由守卫：离开前
  beforeRouteLeave(to, from, next) {
    // console.log('beforeRouteLeave 执行',to, from);
    if(to.path != "/projectDigital/details"){
        localStorage.removeItem('projectQueryParam');
    }
    next();
  }
});
</script>

<style lang="scss" scoped>
.loading-container{
    background-color: rgba(0, 0, 0, 0.7) !important;
    z-index: 1000000;
    .container{
        width: 50%;
        .loading-icon{
            // width: ;
            display: block;
            text-align: center;
            height: 180px;
            margin-bottom: -20px;
            background: none;
            img{
                height: 100%;
            }
            // :deep(.el-loading-mask){
            //     background: none;
            // }
        }
        .txt{
            color: #fff; 
        }
        .text{
            text-align: center;
            color: var(--el-color-primary);
            margin-bottom: 20px;
            font-size: 18px;
        }
    }
}
</style>